<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
</head>
<title>iot</title>
<link rel="stylesheet" type="text/css" th:href="@{/plugins/codemirror/lib/codemirror.css}"/>
<link rel="stylesheet" type="text/css" th:href="@{/plugins/codemirror/theme/nord.css}"/>
<script type="text/javascript" th:src="@{/javascript/jquery-2.1.4.js}"></script>
<script type="text/javascript" th:src="@{/plugins/layui/layui.js}"></script>

<script type="text/javascript" th:src="@{/plugins/codemirror/lib/codemirror.js}"></script>
<script type="text/javascript" th:src="@{/plugins/codemirror/mode/javascript/javascript.js}"></script>
<script type="text/javascript" th:src="@{/plugins/codemirror/addon/display/autorefresh.js}"></script>
<script type="text/javascript" th:src="@{/plugins/codemirror/formatting.js}"></script>


<link rel="stylesheet" type="text/css" th:href="@{/plugins/layui/css/layui.css}"/>

<style>
    body{margin: 10px;}
    .success{
        background-color: #79C48C;
    }
    .demo-carousel{height: 200px; line-height: 200px; text-align: center;}
    .layui-table-box{
        max-height: 300px;
        overflow: scroll;
    }
    .site-demo-laytpl {
        display: inline-block;
        text-align: center;
        width: 46%;
    }
    .layui-form-switch{
        margin-top: 0px;
    }
    .site-demo-laytpl textarea {
        height: 300px;
        border: none;
        background-color: #3F3F3F;
        color: #E3CEAB;
        font-family: Courier New;
        resize: none;
    }
    .site-demo-laytpl div span {
        display: inline-block;
        text-align: center;
        background: #101010;
        color: #fff;
    }
    .site-demo-laytpl textarea, .site-demo-laytpl div span {
        width: 100%;
        padding: 15px;
        margin: 0 15px;
    }
</style>
<html>
<body>
<div class="layui-col-md12" style="line-height:50px;color:#fff;background-color: #79C48C;">
    <div class="grid-demo grid-demo-bg12" style="padding-left: 50px;">iot模版数据;「smart_energy_iot库数据。」</div>
</div>
<div style="padding-top: 40px;width: 90%;width: auto">
    <table id="iotParse" lay-filter="iotParse"></table>
</div>

<div id="addOrUpdate" style="display: none">
    <div class="layui-form-item">
        <label class="layui-form-label">模板标题</label>
        <div class="layui-input-block">
            <input id="title" type="text" name="title" lay-verify="title" autocomplete="off" placeholder="请输入标题" class="layui-input" style="float: left;width: 50%;">
            <div id="operation" style="float: right;width: 40%;">
                <button style="float: inherit;" class="layui-btn" onclick="addOrUpdate()">保存</button>
                <button type="button" style="margin-right: 20px;float: inherit;" class="layui-btn layui-btn-primary" onclick="cancel()">取消</button>
            </div>
        </div>
    </div>
    <div class="layui-col-md12" style="margin:20px 0 20px;line-height:50px;color:#fff;background-color: #79C48C;">
        <div class="grid-demo grid-demo-bg12" style="padding-left: 50px;">jsonbody【数据发送模板】<button type="button" onclick="format(0)" class="layui-btn">格式化</button></div>
    </div>
    <textarea id="editor" name="editor"></textarea>

    <div class="layui-col-md12" style="margin:20px 0 20px;line-height:50px;color:#fff;background-color: #79C48C;">
        <div class="grid-demo grid-demo-bg12" style="padding-left: 50px;">jsonParse【解析模板：】
            <button type="button"  onclick="format(1)"  class="layui-btn">格式化</button>
            <form class="layui-form" action="" style="width:30%;float: right">
                <div class="layui-form-item">
                    <label class="layui-form-label"></label>
                    <div class="layui-input-block">
                        <input type="checkbox" checked="" name="switch" lay-skin="switch" lay-filter="switchTest" lay-text="使用json模式|使用视图模式">
                    </div>
                </div>
            </form>
        </div>
    </div>
    <div id="bodyData" ><textarea id="editorParse" name="editorParse"></textarea></div>
    <textarea class="site-demo-text" style="display: none" id="tpl">
        <div id="f1" class="layui-fluid" style="width:1300px;">
        <h3 style="padding: 15px;background: #e2e2e2;  text-align: center;  font-weight: 400;" >解析属性值:{{d.body.serviceId}}</h3>
        <input style="display: none" id="serviceId_parse" value="{{ d.body.serviceId}}" disabled>
        <div style="height:325px; overflow: scroll;background-color: #2d6e6a;">
            <ul>
                {{#  layui.each(d.servicePropertiesList, function(index, item){ }}
                <li style="">
                    <form id="{{ item.modname }}">
                        <div style="height: 50px;line-height: 50px;background-color: #203a38;"><span style="padding-left: 10px;font-weight: 500;color: #c7a7a7">参数名：{{ item.modname }}</span></div>
                        <div style="height: 50px;line-height: 50px;padding: 5px; background-color: #63b8b3;">
                            <input style="display: none"  name="{{ 'default_'+item.modname  }}" value="{{ item.alias }}">
                            <input disabled="disabled" style="width: 50px"  name="{{ 'dataType_'+item.modname  }}" value="{{ item.dataType }}">
                            <span name="{{ 'default_'+item.modname  }}" style="color: #3b0202;margin-right: 10px;">默认值：{{ item.alias }}</span>
                            {{# if(item.enable==1||item.enable==undefined||item.enable==null){ }}
                            开启随机: <input name="{{ 'random_enable_'+item.modname  }}"  style="margin-right: 10px;" type="checkbox" value="1"  checked>
                            {{# }else{ }}
                            开启随机: <input name="{{ 'random_enable_'+item.modname  }}"  style="margin-right: 10px;" type="checkbox" value="0">
                            {{# } }}
                            {{#  if( item.modname.includes('SOC') ){ }}
                                <input name="{{ 'random_trend_'+item.modname  }}"  style="display: none"  value="{{item.trend==null?1:item.trend}}" >
                                <select id="select" onchange="selectChange({{ 'random_trend_'+item.modname }},this)">
                                    {{#  if(item.trend== -1){ }}
                                    <option value="1" >递增↑</option>
                                    <option value="-1" selected>递减↓</option>
                                    {{#  }else{ }}
                                    <option value="1" selected>递增↑</option>
                                    <option value="-1">递减↓</option><option value="1" >递增↑</option>
                                {{#  } }}
                            </select>
                            {{# }}
                            步长: <input  style="width: 50px;" type="number" name="{{ 'random_size_'+item.modname  }}" value="{{item.size}}">
                            随机数Min: <input  style="width: 100px;" type="number" name="{{ 'random_min_'+item.modname  }}" value="{{ item.min }}">
                            随机数Max: <input style="width: 100px;" type="number" name="{{ 'random_max_'+item.modname  }}" value="{{ item.max }}">
                            {{#  }else{ }}
                            随机数Min: <input  style="width: 100px;" type="number" name="{{ 'random_min_'+item.modname  }}" value="{{ item.min }}">
                            随机数Max: <input style="width: 100px;" type="number" name="{{ 'random_max_'+item.modname  }}" value="{{ item.max }}">
                            {{#  } }}
                            {{# if(item.enum_enable==1){ }}
                            随机时使用以下枚举: <input name="{{ 'random_enable_enumList_'+item.modname  }}"  style="margin-right: 10px;" type="checkbox" value="1"  checked>
                            {{# }else{ }}
                            随机时使用以下枚举: <input name="{{ 'random_enable_enumList_'+item.modname  }}"  style="margin-right: 10px;" type="checkbox" value="0">
                            {{# } }}
                            <!--                            <input name="{{ 'random_enum_'+item.modname  }}"  style="display: none"  value="0"  >-->
                            <select style="width: 50px;" id="{{ 'random_enable_enumList_select_'+item.modname  }}" onchange="">
                                {{#  layui.each(item.enumList, function(index, item2){ }}
                                <option value="{{item2}}" >{{item2}}</option>
                                {{# });}}
                            </select>
                            <a style="background-color: #203a38"  id="{{'add_'+item.modname}}" class="layui-btn layui-btn-xs layui-btn-normal" onclick="addEnumInput({{item.modname}},this)">添加枚举值</a>
                        </div>
                    </form>
                </li>
                {{#  }); }}
                {{#  if(d.servicePropertiesList.length === 0){ }}
                ⽆数据
                {{#  } }}
            </ul>
        </div>
    </div>
    </textarea>
    <div id="bodyData2" style="overflow: scroll;display: none"></div>
</div>
<div style="padding-top: 50px;">
</div>




</body>
<script th:inline="none" type="text/javascript">
    var updateId= -1;
    var show = false;
    let dataSaveOrUpdate = {"title":"","body":"","parse":""};
    var editorTextarea = document.getElementById('editor');
    var editorParseTextarea = document.getElementById('editorParse');
    var initValue = JSON.stringify(dataSaveOrUpdate);
    var myJsonCodeMirror = CodeMirror.fromTextArea(editorTextarea, {

        mode:"application/json",
        theme:"nord",// 主题
        lineNumbers:true,// 显示行号
        smartIndent: true , //智能缩进
        indentUnit: 4, // 智能缩进单位为4个空格长度
        indentWithTabs:true,  // 使用制表符进行智能缩进
        lineWrapping:true,//
        // 在行槽中添加行号显示器、折叠器、语法检测器`
        gutters: ["CodeMirror-linenumbers","CodeMirror-foldgutter","CodeMirror-lint-markers"],
        foldGutter:true, // 启用行槽中的代码折叠
        autofocus:true,  //自动聚焦
        matchBrackets:true,// 匹配结束符号，比如"]、}"
        autoCloseBrackets: true , // 自动闭合符号
        styleActiveLine:true, // 显示选中行的样式
        autoRefresh: true,
        // readOnly: true, //是否只读
        //快捷键
        extraKeys:{
            "F7": function autoFormat(editor) {
                var totalLines = editor.lineCount();
                editor.autoFormatRange({line:0, ch:0}, {line:totalLines});
            }
        },

    });
    //==============================================================
    myJsonCodeMirror.setOption("value", initValue);
    // myJsonCodeMirror.on('blur', () => {
    //     myJsonCodeMirror.save();
    // });
    //=============================================================
    var myParseCodeMirror = CodeMirror.fromTextArea(editorParseTextarea, {

        mode:"application/json",
        theme:"nord",// 主题
        lineNumbers:true,// 显示行号
        smartIndent: true , //智能缩进
        indentUnit: 4, // 智能缩进单位为4个空格长度
        indentWithTabs:true,  // 使用制表符进行智能缩进
        lineWrapping:true,//
        // 在行槽中添加行号显示器、折叠器、语法检测器`
        gutters: ["CodeMirror-linenumbers","CodeMirror-foldgutter","CodeMirror-lint-markers"],
        foldGutter:true, // 启用行槽中的代码折叠
        autofocus:true,  //自动聚焦
        matchBrackets:true,// 匹配结束符号，比如"]、}"
        autoCloseBrackets: true , // 自动闭合符号
        styleActiveLine:true, // 显示选中行的样式
        // readOnly: false, //是否只读
        autoRefresh: true, // 重点是这句，为true
        //快捷键
        extraKeys:{
            "F7": function autoFormat(editor) {
                var totalLines = editor.lineCount();
                editor.autoFormatRange({line:0, ch:0}, {line:totalLines});
            }
        },

    });
    myParseCodeMirror.setOption("value", initValue);
    myParseCodeMirror.on('blur', () => {
        myParseCodeMirror.save();
    });
    myJsonCodeMirror.on('blur', () => {
        myJsonCodeMirror.save();
        console.log(myJsonCodeMirror.getValue());
        try {
            let json = JSON.parse(myJsonCodeMirror.getValue());
            console.log(json);
            let jsonparse = JSON.parse(myParseCodeMirror.getValue());
            let serviceProperties = json.body.serviceProperties;
            for (let item in serviceProperties) {
                if (!jsonparse.hasOwnProperty(item)) {
                    let value = {
                        "default": serviceProperties[item]!=null?serviceProperties[item]:"0",
                        "enable":1,
                        "dataType":"decimal",
                        "min":0,
                        "max":100,
                        "enum_enable":0
                    };
                    if(item.includes("SOC")){
                        value["trend"] = 1;
                        value["size"] = 0.1;
                    }
                    jsonparse[item] = value;
                }
            }
            for(let item in jsonparse){
                if(!serviceProperties.hasOwnProperty(item)){
                    delete jsonparse[item];
                }
            }
            myParseCodeMirror.setValue(JSON.stringify(jsonparse, null, 4));
            parse();
        } catch (e) {
        }
    });

    function selectChange(obj,val){
        obj.value = val.value;
    };
    function addEnum(obj){
        console.log(obj);
        let id = $(obj).attr("forAttr");
        let enumAttr = $("#add_value_"+id).val();
        if (enumAttr == ""||enumAttr == null||enumAttr.length == 0){
            layer.msg("请输入枚举值", function(){
            });
        }else{
            let html = `<option value="${enumAttr}">${enumAttr}</option>`;
            let returnFlag = false;
            $('#random_enable_enumList_select_'+id+" option").each(function(){
                if ($(this).val() == enumAttr){
                    layer.msg("枚举值已存在", function(){
                    });
                    returnFlag = true;
                    return false;
                }
            });
            if (returnFlag){
                return;
            }
            $('#random_enable_enumList_select_'+id).append(html);
            $(obj).parent().find('#add_value_'+id).remove();
            $(obj).parent().find('#add_yes_'+id).remove();
            $('#add_'+id).html("添加枚举值") ;
            layer.msg("添加成功");
        }
    };

    function addEnumInput(modname,obj){
        let id ="random_enable_enumList_"+modname.id;
        if(obj.innerHTML == "添加枚举值"){
            let html = `<input  style="width: 50px;" type="number" id="${'add_value_'+modname.id}" value="">`
                + `<a style="background-color: #155037"  id="${'add_yes_'+modname.id}" class="layui-btn layui-btn-xs layui-btn-normal" onclick="addEnum(this)">确定</a>`
            $(obj).parent().append(html);
            $('#add_yes_'+modname.id).attr('forAttr',modname.id);
            obj.innerHTML = "取消";
        }else{
            $(obj).parent().find('#add_value_'+modname.id).remove();
            $(obj).parent().find('#add_yes_'+modname.id).remove();
            obj.innerHTML = "添加枚举值";
        }
    };
    //=============================================================

    var  layer = layui.layer //弹层
        ,laypage = layui.laypage //分页
        ,laydate = layui.laydate //日期
        ,table = layui.table //表格
        ,carousel = layui.carousel //轮播
        ,upload = layui.upload //上传
        ,element = layui.element //元素操作
        ,slider = layui.slider //滑块
        ,dropdown = layui.dropdown //下拉菜单
        ,laytpl=layui.laytpl
    ,form = layui.form;
    var status =0;
    function parse(){
        try{
            let servicePropertiesList =[];
            var Value = myParseCodeMirror.getValue();
            var myJson = myJsonCodeMirror.getValue();
            var jsonObj = JSON.parse(Value);
            var myJsonObj = JSON.parse(myJson);
            for(var item in jsonObj){
                jsonObj[item]["modname"] = item;
                jsonObj[item]["alias"] = jsonObj[item].default;
                jsonObj[item]["enumList"] = jsonObj[item].enum!=null?jsonObj[item].enum:[];
                servicePropertiesList.push(jsonObj[item]);
            };

            myJsonObj["servicePropertiesList"] = servicePropertiesList;
            console.log("parse",myJsonObj);
            var html = laytpl(tpl.value).render(myJsonObj);
            $("#bodyData2").html(html);
            if($("#operation").css("display")=="none"){
                $("#bodyData2 :input").prop("disabled", true);
                $("#bodyData2 a").hide();
            }
        } catch(e){
            $("#bodyData2").html('<span style="color: #c00;">'+ e.toString() + '</span>');
        }
    }
    $(function () {
        //加载模块
        layui.use(['layer', 'laytpl','table'],function(){ //亦可加载特定模块：layui.use(['layer', 'laydate', function(){// //得到各种内置组件
            //监听指定开关
            form.on('switch(switchTest)', function(data){
                // (this.checked ? 'true' : 'false');

                if(this.checked){
                    layer.msg('使用json模式', {
                        offset: '6px'
                    });
                    status=0;
                    $("#bodyData2").fadeOut();
                    $("#bodyData").fadeIn();
                    if($("#operation").css("display")!="none"){
                        let jsonparse = getParseJson();
                        myParseCodeMirror.setValue(JSON.stringify(jsonparse, null, 4));
                        console.log("使用json模式",jsonparse);
                    }
                }else{
                    layer.msg('使用视图模式', {
                        offset: '6px'
                    });
                    status=1;
                    $("#bodyData").fadeOut();
                    parse();
                    $("#bodyData2").fadeIn();
                }
            });

            // parse();
            // var getTpl = demo.innerHTML
            //     ,view = document.getElementById('bodyData2');
            // laytpl(getTpl).render(document.getElementById('editorParse').value, function(html){
            //     view.innerHTML = html;
            // });

            // layui.each(document.getElementById('editorParse'), function(index, item){
            //     item.onkeyup = function(){
            //         parse();
            //     }
            // });

            //执行一个 table 实例================================
            table.render({
                elem: '#iotParse'
                // ,height: 400
                ,url: '/iot/parse/list' //数据接口
                ,title: '模版数据'
                ,page: false //开启分页
                ,toolbar: true
                ,data: []
                ,toolbar: 'default' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
                ,cols: [[ //表头
                    {type: 'checkbox', fixed: 'left'}
                    ,{type: 'numbers', title: '序号', align: 'center', width: 100, fixed: 'left'}
                    ,{field: 'title', title: '模板名称',  width: 150,align: 'center',fixed: 'left'}
                    , {title: '操作',width: 130, templet: setOperates, align: "center",fixed: 'left'}
                    ,{field: 'id', title: 'id',  width: 100,align: 'center'}
                    , {field: 'serviceId', width: 150, title: '服务id', align: 'center'}
                    , {field: 'updateTime', width: 180, title: '更新时间', align: 'center'}
                    , {field: 'createTime', width: 180, title: '创建时间', align: 'center'}
                    // ,{fixed: 'right', width: 150, align:'center', toolbar: '#barDemo'}
                ]]
            });
            //执行一个 table 实例================================
            //监听头工具栏事件
            table.on('toolbar(iotParse)', function(obj){
                var checkStatus = table.checkStatus(obj.config.id)
                    ,data = checkStatus.data; //获取选中的数据
                switch(obj.event){
                    case 'add':
                        // layer.msg('添加');
                        addParse();
                        break;
                    case 'update':
                        if(data.length === 0){
                            layer.msg('请选择一行');
                        } else if(data.length > 1){
                            layer.msg('只能同时编辑一个');
                        } else {
                            layer.alert('编辑 [id]：'+ checkStatus.data[0].id);
                            update(checkStatus.data[0]);
                        }
                        break;
                    case 'delete':
                        if(data.length === 0){
                            layer.msg('请勾选一行');
                        } else {
                            layer.open({
                                type: 1,
                                title: '删除',
                                content: `<div style='margin:20px;display:flex;justify-content:center;'>确定删除所选模板吗？</div>`,
                                btn: ['确定', '取消'],
                                yes: function(index, layero){
                                    layer.close(index);
                                    let ids = [];
                                    for(let i = 0; i < data.length; i++){
                                        ids.push(data[i].id);
                                    }
                                    console.log(data);
                                    ajax("/iot/parse/delete",ids,function (data, status) {
                                        if (data.code == 0) {
                                            layer.msg("删除成功");
                                            $("#addOrUpdate").fadeOut();
                                            table.reload('iotParse');
                                        } else {
                                            layer.msg("删除失败:"+data.msg, function(){
                                            });
                                        }
                                    });
                                },
                                btn2: function(index, layero){
                                    layer.close(index);
                                }
                            });
                        }
                        break;
                };
            });

            //table行选中
            table.on('row(iotParse)', function (obj) {//datafilter是table的lay-filter属性
                console.log(obj.data);
                //判断是否被选中
                if (obj.tr.find('.layui-form-checkbox').hasClass('layui-form-checked')) {
                    $(obj.tr).addClass('success');
                    // $(obj.tr).addClass('success'); //添加当前选中的 success样式用于区别
                }else{
                    $(obj.tr).removeClass('success');
                    // $('.success').removeClass('success'); //去除之前选中的行的，选中样式
                }



                $("#operation").css("display","none");
                myJsonCodeMirror.setOption("readOnly", true);
                myParseCodeMirror.setOption("readOnly", true);
                $("#title").attr("readOnly","true");
                getIotParseInfo(obj.data.id);
            });

            //监听工具条========================================
            function setOperates(data) {
                let id = data.id;
                var btn = "";
                btn += `<a  lay-event="useParse" class="layui-btn layui-btn-xs layui-btn-green" )">应用该模板</a> `
                return btn;
            };
            //监听行工具条========================================

            //监听行工具事件=============================================================
            table.on('tool(iotParse)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                let layEvent = obj.event; //获得 lay-event 对应的值

                $('.success').removeClass('success'); //去除之前选中的行的，选中样式
                $(obj.tr).addClass('success'); //添加当前选中的 success样式用于区别

                if(layEvent === 'useParse'){
                   console.log(obj.data);
                    layer.confirm('确定要应用该模板吗？', function(index){
                        toParent(obj.data);
                        // layer.close(index);
                        // $.ajax({
                        //     url: '/iot/parse/useParse',
                        //     type: 'post',
                        //     data: {
                        //         id: obj.data.id
                        //     },
                        //     success: function (res) {
                        //         if (res.code === 0) {
                        //             layer.msg('应用成功');
                        //             setTimeout(function () {
                        //                 window.location.reload();
                        //             }, 1000);
                        //         } else {
                        //             layer.msg(res.msg);
                        //         }
                        //     }
                        // });
                    });
                }
            });
            //监听单元格事件=============================================================
            function ajax(url,data,callback){
                $.ajax({
                    dataType:'json',
                    contentType: "application/json; charset=utf-8",
                    url: url,
                    type: "POST",
                    data: JSON.stringify(data),
                    // data: data,
                    success: function (data, status) {
                        callback(data,status);
                    },
                    error:function(msg) {     //请求失败后要执行的代码
                        alert("请求失败"+msg);
                    }
                    // success: function (data) {
                    //     if (data.code == 0) {
                    //         layer.msg("启动成功");
                    //         table.reload('iot');
                    //     } else {
                    //         layer.msg("启动失败:"+data.msg, function(){
                    //         });
                    //     }
                    // }
                });
            }

            function addParse(){
                $("#addOrUpdate").fadeIn();
                $("#operation").fadeIn();
                myJsonCodeMirror.setOption("readOnly", false);
                myParseCodeMirror.setOption("readOnly", false);
                $("#title").attr("readOnly",false);
                removeData();
            }

        });


    });
    function getIotParseInfo(id){
        $.get(`/iot/parse/info/${id}`,function(data,status){
            console.log(data);
            if (data.code == 0) {
                $("#addOrUpdate").fadeIn();
                dataSaveOrUpdate = data.data;
                loadingData(dataSaveOrUpdate);
                parse();
                // if(!show){

                // }
            } else {
                layer.msg("获取模板信息失败"+data.msg, function(){
                });
            }
        });
    };

    function loadingData(data){
        $("#title").val(data.title);
        myJsonCodeMirror.setValue(data.jsonBody);
        myParseCodeMirror.setValue(data.jsonParse);
        // var totalLines2 = myParseCodeMirror.lineCount();
        // myJsonCodeMirror.autoFormatRange({line:0, ch:0}, {line:totalLines});
        // myParseCodeMirror.autoFormatRange({line:0, ch:0}, {line:totalLines2});
    }

    function format(num){
        let mirror;
        let id = "";
        if(num == 0){
            mirror = myJsonCodeMirror;
            id = "editor";
        }else if(num ==1){
            mirror = myParseCodeMirror;
            id = "editorParse";
        }
        mirror.save();
        let json = document.getElementById(id).value;
        console.log(json);
        if(!isJSON(json)){
            layer.msg("请输入正确的json格式", function(){
            });
            return;
        }

        var totalLines = mirror.lineCount();
        mirror.autoFormatRange({line:0, ch:0}, {line:totalLines});
    }

    function isJSON(str) {
        if (typeof str == 'string') {
            try {
                var obj=JSON.parse(str);
                if(typeof obj == 'object' && obj ){
                    return true;
                }else{
                    return false;
                }

            } catch(e) {
                return false;
            }
        }
    }

    function cancel(){
        dataSaveOrUpdate = {};
        removeData();
        $("#addOrUpdate").fadeOut();
    }
    function removeData(){
        show = false;
        updateId = -1;
        dataSaveOrUpdate = {};
        let init ={
            "body":{
                "serviceId":"",
                "serviceProperties":{
                }
            },
            "token":"",
            "timestamp":""
        };
        // myJsonCodeMirror.setOption("value", JSON.stringify(init, null, 4));
        myJsonCodeMirror.setValue(JSON.stringify(init, null, 4));
        myJsonCodeMirror.save();
        myJsonCodeMirror.refresh();
        myParseCodeMirror.setValue('{}');
        myParseCodeMirror.save();
        myParseCodeMirror.refresh();
        $("#title").val('');
    }
    function update(data){
        updateId = data.id;
        $("#addOrUpdate").fadeIn();
        $("#operation").fadeIn();
        myJsonCodeMirror.setOption("readOnly", false);
        myParseCodeMirror.setOption("readOnly", false);
        $("#title").attr("readOnly",false);
        getIotParseInfo(data.id);

    }

    function addOrUpdate(){
        if(status == 0){
        }else if(status == 1){
            let jsonparse = getParseJson();
            myParseCodeMirror.setValue(JSON.stringify(jsonparse, null, 4));
        }
        if(updateId == -1){
            addData();
        }else{
            updateData();
        }
    }
    function addData(){
        var title = $("#title").val();
        var jsonBody = myJsonCodeMirror.getValue();
        var jsonParse = myParseCodeMirror.getValue();

        if(!check(title,jsonBody,jsonParse)){
            return;
        };
        if(!checkRule(jsonBody,jsonParse)){return;};
        let serviceId = JSON.parse(jsonBody).body.serviceId;

        let data = {
            "title":title,
            "jsonBody":JSON.stringify(JSON.parse(jsonBody)),
            "jsonParse":JSON.stringify(JSON.parse(jsonParse)),
            "serviceId":serviceId
        };
        ajax(`/iot/parse/save`,data,function(data,status){
            console.log(data);
            if (data.code == 0) {
                layer.msg("添加成功");
                removeData();
                $("#addOrUpdate").fadeOut();
                table.reload('iotParse');
            } else {
                layer.msg("添加失败"+data.msg, function(){
                });
            }
        });
    }

    function check(title,jsonBody,jsonParse){
        if(!title){
            layer.msg("请输入标题", function(){
            });
            return false;
        }
        if(!jsonBody){
            layer.msg("请输入jsonBody", function(){
            });
            return false;
        }
        if(!jsonParse){
            layer.msg("请输入jsonParse", function(){
            });
            return false;
        }
        if(!isJSON(jsonParse)){
            layer.msg("jsonParse请输入正确的json格式", function(){
            });
            return false;
        }
        if(!isJSON(jsonBody)){
            layer.msg("jsonParse请输入正确的json格式", function(){
            });
            return  false;
        }

        return true;
    }

    function checkRule(jsonBody,jsonParse){
        let data =JSON.parse(jsonBody);
        let parse =JSON.parse(jsonParse);
        if(!data.hasOwnProperty("body")){
            layer.msg("jsonBody参数需包含body数据体！", function(){
            })
            return false;
        }
        let serviceId = data.body.serviceId;
        let servicePropertiesList = data.body.serviceProperties;
        if(serviceId==undefined||serviceId==null||serviceId==""){
            layer.msg("未正常解析得到serviceId，请确认是否输入正确！", function(){
            });
            return false;
        }
        if(servicePropertiesList==undefined||servicePropertiesList==null){
            layer.msg("未正常解析得到serviceProperties，请确认是否输入正确！", function(){
            });
            return false;
        }
        if(Object.keys(servicePropertiesList).length!=Object.keys(parse).length){
            layer.msg("jsonParse和jsonBody无法匹配，请确认是否输入正确！", function(){
            });
            return false;
        }
        for(let serviceProperties in servicePropertiesList){
            if(!parse.hasOwnProperty(serviceProperties)){
                layer.msg(`jsonParse和jsonBody无法匹配，缺失参数${serviceProperties}.请确认是否输入正确！ `, function(){
                });
                return false;
            }else{
                let serviceParse = parse[serviceProperties];
                if(!serviceParse.hasOwnProperty("default")){
                    layer.msg(`jsonParse ${serviceProperties}缺失必要参数default即默认值.请确认是否输入正确！ `, function(){
                    });
                    return false;
                }
                if(!serviceParse.hasOwnProperty("enable")){
                    layer.msg(`jsonParse ${serviceProperties}缺失必要参数enable即是否开启随机值，0不开启，1开启.请确认是否输入正确！ `, function(){
                    });
                    return false;
                }
                if(!serviceParse.hasOwnProperty("dataType")){
                    layer.msg(`jsonParse ${serviceProperties}缺失必要参数dataType即参数类型，string，decimal，int.请确认是否输入正确！ `, function(){
                    });
                    return false;
                }
                if(!serviceParse.hasOwnProperty("min")){
                    layer.msg(`jsonParse ${serviceProperties}缺失必要参数min即随机时所取最小值.请确认是否输入正确！ `, function(){
                    });
                    return false;
                }
                if(!serviceParse.hasOwnProperty("max")){
                    layer.msg(`jsonParse ${serviceParse}缺失必要参数min即随机时所取最大值.请确认是否输入正确！ `, function(){
                    });
                    return  false;
                }
            }
        }
        for(let item in parse){
            if(parse[item].dataType!="string"&&parse[item].dataType!="decimal"&&parse[item].dataType!="int"){
                if(parse[item].dataType!="string"){
                    layer.msg(`jsonParse ${item}的dataType 不支持，请确认是否输入正确！ `, function(){
                    });
                    return false;
                }
            }
            if(!isNumber(parse[item].default)){
                if(parse[item].dataType!="string"&&parse[item].enable!=0){
                    layer.msg(`jsonParse ${item}的default值不为数字，但dataType不为string，请确认是否输入正确！ `, function(){
                    });
                    return false;
                }
            }
        }
        return true;
    }
    function isNumber(val){
        var regPos = /^[0-9]+.?[0-9]*/; //判断是否是数字。
        if(regPos.test(val) ){
            return true;
        }else{
            return false;
        }
    }

    function updateData(){
        var jsonBody = myJsonCodeMirror.getValue();
        var jsonParse = myParseCodeMirror.getValue();
        var title = $("#title").val();

        if(!check(title,jsonBody,jsonParse)){return;};
        if(!checkRule(jsonBody,jsonParse)){return;};
        let serviceId = JSON.parse(jsonBody).body.serviceId;
        if(serviceId==undefined || serviceId==""){
            layer.msg("请填写serviceId！");
            return;
        }
        let data = {
            "id":updateId,
            "title":title,
            "jsonBody":JSON.stringify(JSON.parse(jsonBody)),
            "jsonParse":JSON.stringify(JSON.parse(jsonParse)),
            "serviceId":serviceId
        };
        ajax(`/iot/parse/update`,data,function(data,status){
            console.log(data);
            if (data.code == 0) {
                layer.msg(`修改${updateId}数据保存成功`);
                removeData();
                $("#addOrUpdate").fadeOut();
                table.reload('iotParse');
            } else {
                layer.msg("修改保存失败"+data.msg, function(){
                });
            }
        });
    }

    function ajax(url,data,callback){
        $.ajax({
            dataType:'json',
            contentType: "application/json; charset=utf-8",
            url: url,
            type: "POST",
            data: JSON.stringify(data),
            // data: data,
            success: function (data, status) {
                callback(data,status);
            },
            error:function(msg) {     //请求失败后要执行的代码
                alert("请求失败"+msg);
            }
            // success: function (data) {
            //     if (data.code == 0) {
            //         layer.msg("启动成功");
            //         table.reload('iot');
            //     } else {
            //         layer.msg("启动失败:"+data.msg, function(){
            //         });
            //     }
            // }
        });
    }

    function getParseJson(){
        let jsonBody = {};
        let div = document.getElementById("f1");
        // let serviceId = document.getElementById("serviceId_parse").value;
        let forms = div.getElementsByTagName('form');

        for (let i = 0; i < forms.length; i++) {
            let name =forms[i].id;
            let tagElements = forms[i].getElementsByTagName('input');
            let enumFlag = false;
            let json = {};
            for (var j = 0; j < tagElements.length; j++) {
                let _name = tagElements[j].name;

                let value = tagElements[j].value;
                if(tagElements[j].type == 'checkbox'){
                    let itemName ="enable"
                    let checkName = tagElements[j].name;
                    if(checkName.includes("enum")){
                        itemName = "enum_enable";
                    }
                    if(tagElements[j].checked){
                        json[itemName] = 1;
                        if(itemName == "enum_enable"){
                            enumFlag = true;
                        }
                    }else{
                        json[itemName] = 0;
                    }
                }else{
                    if(_name.indexOf("random_min_")==0){
                        json["min"] = value;
                    }else if(_name.indexOf("random_max_")==0){
                        json["max"] = value;
                    }else if(_name.indexOf("default_")==0){
                        json["default"] = value;
                    }else if(_name.includes("trend")){
                        json["trend"]= value;
                    }else if(_name.includes("size")){
                        json["size"]= value;
                    }else if(_name.includes("dataType")){
                        json["dataType"]= value;
                    }
                }

                if(enumFlag){
                    let id = forms[i].getElementsByTagName('select')[0].id;
                    if ($("#"+id+" option").length >0){
                        let enumList = [];
                        $("#"+id+" option").each(function(){
                            enumList.push($(this).val());
                        });
                        json["enum"] = enumList;
                    }
                }
            }
            jsonBody[name] = json;
        }
        // console.log("jsonBody",jsonBody);
        // console.log(JSON.stringify(jsonBody));
        return jsonBody;
    };


    //子=>父
    function toParent(data){
        //注意：parent 是 JS 自带的全局对象，可用于操作父页面
        var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
        //在父层弹出一个层
        parent.layer.msg(`使用模板   [${data.title}]`, {shade: 0.3})
        parent.fromSonParse(data);
        // parent.layer.tips('Look here', '#parentIframe', {time: 5000});
        parent.layer.close(index);
    }


</script>

</html>



